<template>
  <!-- 新增活动 -->
  <el-dialog
    v-model="visible"
    :title="form.priceId ? '修改定价捆绑活动' : '新增定价捆绑活动'"
    class="addGroupBuy"
    width="1000px"
    center
    top="10vh"
    :close-on-click-modal="false"
    @close="close"
  >
    <!-- 新增用户 -->
    <div class="addGroupBuyBox">
      <el-form
        ref="ruleFormRef"
        class="formBox"
        :model="form"
        label-width="150px"
        :rules="rules"
      >
        <el-form-item label="活动名称" prop="composeName">
          <el-input
            v-model="form.composeName"
            maxlength="15"
            minlength="2"
            show-word-limit
            placeholder="请输入活动名称"
            oninput="value=value.replace(/\s+/g, '')"
            style="max-width: 500px;"
          />
        </el-form-item>
        <el-form-item class="timeDataBox" label="活动时间" prop="dateInfo">
          <el-date-picker
            v-model="formExtra.dateInfo"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="max-width: 400px;"
            @change="changeDate"
          />
        </el-form-item>
        <el-form-item
          class="priceRules"
          label="优惠规则"
          prop="priceRules"
        >
          <div
            v-for="(item, index) in formExtra.priceRules"
            :key="index"
            class="item"
          >
            <div class="group">
              任选
              <el-input-number
                v-model="item.number"
                :max="100"
                :min="2"
                :precision="0"
                :step="1"
                @blur="validForm('priceRules')"
              />
              件
            </div>
            <div class="group">
              捆绑价
              <el-input-number
                v-model="item.price"
                :controls="false"
                :max="10000000"
                :min="0.01"
                :precision="2"
                @blur="vildateForm('priceRules')"
              />
              元
            </div>
            <div v-if="index !== 0" class="btnDel">
              <el-button
                type="primary"
                :icon="ElIconDelete"
                @click="delRow(index)"
              />
            </div>
          </div>
          <div class="item" style="padding: 0 12px;">
            <el-button type="primary" @click="addRow">
              添加层级
            </el-button>
          </div>
        </el-form-item>
        <el-form-item class="applyType" label="活动商品" prop="commodity">
          <span
            class="selectBtn"
            @click="chooseProduct"
          >请选择<i
            v-if="form.priceProducts.length !== 0"
            class="selectNum"
          >{{ form.priceProducts.length }}</i></span>
          <div class="selecTable">
            <el-table
              :data="selectTableData"
              border
              :header-cell-style="{ background: '#EEF3FF', color: '#333333' }"
              tooltip-effect="dark"
              style="width: 100%"
            >
              <el-table-column
                prop="productId"
                label="商品id"
                show-overflow-tooltip
              />
              <el-table-column label="商品主图" width="150" align="center">
                <template #default="scope">
                  <img
                    height="80"
                    width="80"
                    :src="scope.row.productImage"
                    alt
                    srcset
                  />
                </template>
              </el-table-column>
              <el-table-column
                prop="productName"
                label="商品名称"
                width="220"
              />
              <el-table-column
                prop="section"
                label="售价区间"
                show-overflow-tooltip
              />
              <el-table-column
                prop="stockNumber"
                label="库存"
                width="120"
                show-overflow-tooltip
              />
              <el-table-column label="操作" show-overflow-tooltip>
                <template #default="scope">
                  <div class="btnList">
                    <el-popconfirm
                      title="确定删除此活动？"
                      @confirm="delProduct(scope.row)"
                    >
                      <template #reference>
                        <el-button
                          class="delCls"
                          link
                          type="danger"
                        >删除</el-button>
                      </template>
                    </el-popconfirm>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="footBtnBox">
        <el-button type="primary" @click="priceSubmit">保 存</el-button>
        <el-button type="danger" @click="goToList">取 消</el-button>
      </div>
    </template>
    <!-- 商品 -->
    <el-dialog
      v-model="productVisible"
      title="选择商品"
      width="55%"
      top="50px"
      class="group-dialog"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      :modal="false"
    >
      <div class="formSearch">
        <el-form :inline="true" :model="productQuery">
          <el-form-item label="商品名称">
            <el-input
              v-model="productQuery.search"
              maxlength="20"
              placeholder="请输入商品名称"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getProList">查询</el-button>
            <el-button type="primary" @click="clear">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 表格 -->
      <div class="tableBox">
        <el-table
          ref="multipleTableRef"
          :data="productData"
          border
          :header-cell-style="{ background: '#EEF3FF', color: '#333333' }"
          tooltip-effect="dark"
          style="width: 100%"
          row-key="skuId"
          max-height="600"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            :reserve-selection="true"
            width="55"
          />
          <el-table-column
            prop="productId"
            label="商品id"
            show-overflow-tooltip
          />
          <el-table-column label="商品主图" width="150" align="center">
            <template #default="scope">
              <img
                height="80"
                width="80"
                :src="scope.row.productImage"
                alt
                srcset
              />
            </template>
          </el-table-column>
          <el-table-column prop="productName" label="商品名称" width="220" />
          <el-table-column
            prop="section"
            label="售价区间"
            show-overflow-tooltip
          />
          <el-table-column
            prop="stockNumber"
            label="库存"
            width="120"
            show-overflow-tooltip
          />
        </el-table>
        <div class="fenye">
          <el-pagination
            :current-page="productQuery.page"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="productQuery.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
      <template #footer>
        <div class="footBtnBox">
          <span>
            <el-button type="primary" @click="saveIdList">确 定</el-button>
            <el-button @click="closeSelect">取 消</el-button>
          </span>
        </div>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup>
import { defineComponent, reactive, ref } from 'vue';
import { Delete as ElIconDelete } from '@element-plus/icons-vue'
import {
  priceAdd,
  priceUpate,
  getPriceDetail,
  getComposeSelectProduct,
} from '@/api/marketing'

// import { getClassifyGetAll } from '@/api/commodity'

defineComponent({
  name: 'ActivityPriceForm'
})

const emit = defineEmits(['reset'])
defineExpose({
  open, close
})

function initForm (data) {
  return {
    priceId: data && data.priceId || 0,
    priceType: data && data.priceType || 1,
    composeName: data && data.composeName || '',
    startTime: data && data.startTime || null,
    endTime: data && data.endTime || null,
    priceProducts: data && data.members || [],
  }
}

const visible = ref(false)
const productVisible = ref(false)
const ruleFormRef = ref()
const form = ref(initForm())
const productQuery = ref({
  search: '',
  page: 1,
  pageSize: 10
})
const total = ref(0)
const productData = ref([])
const multipleTableRef = ref()
const multipleSelection = ref([])

/**
 * @property {array} priceRules
 * @property {array} dateInfo
 */
const formExtra = reactive({
  priceRules: [],
  dateInfo: [],
})

const selectTableData = ref([]);

const rules = {
  composeName: [
    { required: true, message: '请输入活动名称', trigger: 'blur' },
    // {
    //   min: 2,
    //   max: 30,
    //   message: "长度在 2 到 30 个字符",
    //   trigger: "blur",
    // },
  ],
  dateInfo: [
    { required: true, validator: validDate, trigger: 'change' },
  ],
  priceRules: [
    { required: true, validator: validRules, trigger: 'change' },
  ],
  commodity: [
    { required: true, validator: validCommodity, trigger: 'change' },
  ]
}
function validDate (rule, value, callback) {
  if (!formExtra.dateInfo || !formExtra.dateInfo.length) {
    return callback(new Error('请选择活动时间'))
  }
  callback()
}
function validRules (rule, value, callback) {
  if (!formExtra.priceRules.length) {
    return callback(new Error('请添加活动规则'))
  } else {
    let check = false
    formExtra.priceRules.forEach(item => {
      if (!item.number || !item.price) {
        check = true
      }
    })
    if (check) {
      return callback(new Error('请调整活动规则'))
    }
  }
  callback()
}
function validCommodity (rule, value, callback) {
  if (!form.value.priceProducts || !form.value.priceProducts.length) {
    return callback(new Error('请选择活动商品'))
  }
  callback()
}
function validForm (str) {
  if (str) {
    ruleFormRef.value.validateField(str)
  }
}

function open (id) {
  form.value.priceId = id
  if (id) {
    getPriceInfo()
  }
  visible.value = true
}
function close () {
  visible.value = false
  form.value = initForm()
  productQuery.value.page = 1
  formExtra.dateInfo = []
  formExtra.priceRules = []
  selectTableData.value = []
  multipleTableRef.value?.clearSelection()
  ruleFormRef.value?.resetFields()
}

function getPriceInfo () {
  getPriceDetail({ priceId: form.value.priceId }).then(res => {
    form.value.composeName = res.data.composeName
    form.value.startTime = res.data.startTime
    form.value.endTime = res.data.endTime
    form.value.priceType = res.data.priceType
    formExtra.priceRules = res.data.rules
    selectTableData.value = res.data.composeProducts.map((item) => {
      item.productImage = item.image
      item.section = item.sectionPrice
      return item
    })
    selectTableData.value.forEach((i) => {
      form.value.priceProducts.push({
        productId: i.productId,
        priceId: form.value.priceId,
      })
    })
    formExtra.dateInfo = [form.value.startTime, form.value.endTime]
  })
}

function changeDate (e) {
  if (!e) {
    formExtra.dateInfo = []
    return
  }
  var startTime = Date.parse(e[1])
  var timestamp = Date.parse(new Date())
  if (startTime < timestamp) {
    formExtra.dateInfo = []
    ElMessage.warning('活动结束时间不能小于当前时间')
  }
}

// 获取可以选择捆绑的商品
function getProList () {
  getComposeSelectProduct(productQuery.value).then((res) => {
    if (res.code === '') {
      productData.value = res.data.list
      total.value = res.data.total
      for (let i = 0; i < productData.value.length; i++) {
        for (let j = 0; j < selectTableData.value.length; j++) {
          if (
            productData.value[i].productId ===
                selectTableData.value[j].productId
          ) {
            multipleTableRef.value.toggleRowSelection(productData.value[i])
          }
        }
      }
    }
  })
}
function handleCurrentChange (val) {
  productQuery.value.page = val
  getProList()
}
function handleSizeChange (val) {
  productQuery.value.pageSize = val
  getProList()
}

function clear () {
  productQuery.value.search = ''
  getProList()
}
// 选择商品
function chooseProduct () {
  getProList()
  productVisible.value = true
}

function priceSubmit () {
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      form.value.startTime = formExtra.dateInfo[0]
      form.value.endTime = formExtra.dateInfo[1]
      form.value.priceRules = formExtra.priceRules
      let numbers = new Set(form.value.priceRules.map(rule => rule.number));
      if (numbers.size !== form.value.priceRules.length) {
        ElMessage.error('优惠规则任选件数不能重复!')
        return false
      }
      if (form.value.priceId) {
        priceUpate(form.value).then((res) => {
          if (res.code === '') {
            ElMessage.success('修改成功')
            emit('reset')
          } else {
            ElMessage.error(res.message)
          }
        })
      } else {
        priceAdd(form.value).then((res) => {
          if (res.code === '') {
            ElMessage.success('提交成功')
            emit('reset')
          } else {
            ElMessage.error(res.message)
          }
        })
      }
    } else {
      return false
    }
  })
}

// 选中商品
function handleSelectionChange (val) {
  multipleSelection.value = val
}
// 保存选择商品ID
function saveIdList () {
  const idList = []
  selectTableData.value = multipleSelection.value
  multipleSelection.value.forEach((i) => {
    idList.push({
      priceId: form.value.priceId,
      productId: i.productId,
    })
  })
  form.value.priceProducts = idList
  productVisible.value = false
  validForm('commodity')
}
// 取消选择
function closeSelect () {
  productVisible.value = false
}
// 跳转列表
function goToList () {
  emit('reset')
}

// 删除产品
function delProduct (row) {
  var curIndex = 0
  form.value.priceProducts.forEach((item, index) => {
    if (item.productId === row.productId) {
      curIndex = index
    }
  })
  form.value.priceProducts.splice(curIndex, 1)
  selectTableData.value.splice(curIndex, 1)
}
// 增加行
function addRow () {
  formExtra.priceRules.push({
    number: 2,
    price: 0.01,
  })
  validForm('priceRules')
}
// 删除行
function delRow (index) {
  formExtra.priceRules.splice(index, 1)
}
</script>

<style lang="scss" scoped>
.addGroupBuy {
  background: #ffffff;
  .formBox {
    .applyType {
      .selectBtn {
        display: inline-block;
        margin: 0 30px 10px 0;
        width: 100px;
        height: 30px;
        line-height: 30px;
        background: #66b1ff;
        color: #ffffff;
        text-align: center;
        font-size: 14px;
        border-radius: 4px;
        cursor: pointer;
        position: relative;
        i {
          position: absolute;
          right: -10px;
          top: -10px;
          width: 25px;
          height: 25px;
          line-height: 25px;
          background: #ffffff;
          border-radius: 50%;
          border: 1px solid #66b1ff;
          text-align: center;
          color: #3A68F2;
          font-style: normal;
          font-size: 12px;
        }
      }
    }
  }
  .footBtnBox {
    width: 100%;
    display: flex;
    justify-content: center;
    margin-top: 30px;
  }
}
.priceRules {
  .item {
    margin-bottom: 10px;
    .group {
      display: inline-block;
      margin-right: 50px;
      .el-input {
        width: 100px;
      }
    }
    .btnDel {
      display: inline-block;
    }
  }
}
</style>
